// create a fetch wrapper
const fetchService = async (url, options = {}) => {
  // 基础URL
  // const baseUrl = process.env.VUE_APP_BASE_API;
  const baseUrl = 'http://express.cmsya.com/';
  const fullUrl = url.startsWith('http') ? url : `${baseUrl}${url}`;

  // 请求拦截器
  const onRequest = (config) => {
    // 如果请求体是 FormData，则不设置 'Content-Type'
    const isFormData = config.body instanceof FormData;
    return {
      ...config,
      headers: {
        'Authorization-Token': window.localStorage.getItem('Authorization') || '',
        ...config.headers,
        ...(isFormData ? {} : { 'Content-Type': 'application/json' }),
      },
    };
  };

  // 响应拦截器
  const onResponse = async (response) => {
    if (!response.ok) {
      const error = await response.json();
      throw new Error(error.message || `Request failed with status ${response.status}`);
    }
    return response;
  };

  // 处理请求
  const config = onRequest(options);

  try {
    // 发起请求
    const response = await fetch(fullUrl, config);

    // 处理响应
    const processedResponse = await onResponse(response);

    // 解析响应数据
    const res = await processedResponse.json();
    console.log('res', res);
    if(res.success){
      return res.data
    }
    switch (res.code) {
      case 501:
        console.log('请登录');
        setTimeout(() => {
          window.location = '#/login/';
        }, 1500);
        break;
      case 502:
        console.log('网站内部错误，请联系网站维护人员');
        break;
      case 401:
        console.log('参数不对');
        break;
      case 402:
        console.log('参数值不对');
        break;
      case 0:
        return res;
      default:
        // 非5xx的错误属于业务错误，留给具体页面处理
        throw response;
    }
    throw new Error('error');
  } catch (error) {
    console.log('连接超时', error); // for debug
    throw error;
  }
};

export default fetchService;
